package routers

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/plugins/cors"
	"nspel/controllers"
	"nspel/entity"
	"nspel/model"
	"strings"
)

var SjaxAuthorityMap map[string]map[byte]byte
var AjaxAuthorityMap map[string]map[byte]byte

func init() {
	AjaxAuthorityMap = map[string]map[byte]byte{
		"/api/login":                  nil,
		"/api/logout":                 nil,
		"/api/area/import/check":      {entity.ManagerAuthority.Administrator: 1},
		"/api/area/import/submit":     {entity.ManagerAuthority.Administrator: 1},
		"/api/school/import/check":    {entity.ManagerAuthority.Administrator: 1},
		"/api/school/import/submit":   {entity.ManagerAuthority.Administrator: 1},
		"/api/student/import/check":   {entity.ManagerAuthority.Administrator: 1},
		"/api/student/import/submit":  {entity.ManagerAuthority.Administrator: 1},
		"/api/physical/import/check":  {entity.ManagerAuthority.Administrator: 1},
		"/api/physical/import/submit": {entity.ManagerAuthority.Administrator: 1},
		"/api/province/selector":      nil /*{entity.ManagerAuthority.Administrator: 1}*/}
	SjaxAuthorityMap = map[string]map[byte]byte{
		"/login":         nil,
		"/api/area/list": nil,
	}
}

func getRawUri(uri string) string {
	if subIndex := strings.Index(uri, "?"); subIndex > 0 {
		uri = uri[:subIndex]
	}
	return uri
}

var adminPermission = func(c *context.Context) {
	_, ok := c.Input.Session("uid").(int64)
	if !ok {
		c.Redirect(302, "/login")
	}
	authority := c.Input.Session("authority").(byte)
	if authority != entity.ManagerAuthority.Administrator {
		c.ResponseWriter.WriteHeader(403)
		return
	}
}

var provincePermission = func(c *context.Context) {
	_, ok := c.Input.Session("uid").(int64)
	if !ok {
		c.Redirect(302, "/login")
	}
	authority := c.Input.Session("authority").(byte)
	if authority > entity.ManagerAuthority.Province {
		c.ResponseWriter.WriteHeader(403)
		return
	}
}

var needLogin = func(c *context.Context) {
	_, ok := c.Input.Session("uid").(int64)
	if !ok {
		c.Redirect(302, "/login")
	}
}

var loginRedirect = func(c *context.Context) {
	_, ok := c.Input.Session("uid").(int64)
	if ok {
		c.Redirect(302, "/")
	}
}

var adminApiPermission = func(c *context.Context) {
	_, ok := c.Input.Session("uid").(int64)
	if !ok {
		c.Output.JSON(model.ErrorRes{RetCode: 1, Msg: "验证失败"}, false, false)
		return
	} else {
		authority := c.Input.Session("authority").(byte)
		if authority != entity.ManagerAuthority.Administrator {
			c.Output.JSON(model.ErrorRes{RetCode: 1, Msg: "验证失败"}, false, false)
			return
		}
	}
}

var areaApiPermission = func(c *context.Context) {
	_, ok := c.Input.Session("uid").(int64)
	if !ok {
		c.Output.JSON(model.ErrorRes{RetCode: 1, Msg: "验证失败"}, false, false)
		return
	}
	authority := c.Input.Session("authority").(byte)
	if authority > entity.ManagerAuthority.Area {
		c.Output.JSON(model.ErrorRes{RetCode: 1, Msg: "验证失败"}, false, false)
		return
	}
}

var schoolApiPermission = func(c *context.Context) {
	_, ok := c.Input.Session("uid").(int64)
	if !ok {
		c.Output.JSON(model.ErrorRes{RetCode: 1, Msg: "验证失败"}, false, false)
		return
	}
	authority := c.Input.Session("authority").(byte)
	if authority > entity.ManagerAuthority.School {
		c.Output.JSON(model.ErrorRes{RetCode: 1, Msg: "验证失败"}, false, false)
		return
	}
}

var apiNeedLogin = func(c *context.Context) {
	_, ok := c.Input.Session("uid").(int64)
	if !ok {
		c.ResponseWriter.WriteHeader(403)
		return
	}
}

var provinceApiPermission = func(c *context.Context) {
	_, ok := c.Input.Session("uid").(int64)
	if !ok {
		c.ResponseWriter.WriteHeader(403)
		return
	}
	authority := c.Input.Session("authority").(byte)
	if authority > entity.ManagerAuthority.Province {
		c.ResponseWriter.WriteHeader(403)
		return
	}
}

func RoutersInit() {
	beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
		//AllowAllOrigins:  true,
		AllowOrigins:     []string{"http://localhost:8080"},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		AllowCredentials: true,
	}))

	//beego.ErrorController(&controllers.ErrorController{})
	beego.Router("/api/login", &controllers.UserController{}, "POST:PostLogin")
	beego.Router("/api/logout", &controllers.UserController{}, "POST:PostLogout")

	beego.Router("/api/province/selector", &controllers.ProvinceController{}, "GET:GetProvinceSelect")
	beego.InsertFilter("/api/province/selector", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/city/selector", &controllers.CityController{}, "GET:GetCitySelect")
	beego.InsertFilter("/api/city/selector", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/area/list", &controllers.AreasManageController{}, "GET:GetAreasList")
	beego.InsertFilter("/api/area/list", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/area/add", &controllers.AreasManageController{}, "POST:PostAreaAdd")
	beego.InsertFilter("/api/area/add", beego.BeforeRouter, adminPermission)

	beego.Router("/api/area/modify", &controllers.AreasManageController{}, "POST:PostAreaModify")
	beego.InsertFilter("api/area/modify", beego.BeforeRouter, adminPermission)

	beego.Router("/api/username/validate/exist", &controllers.UserController{}, "POST:PostUserNameValidateExist")
	beego.InsertFilter("/api/username/validate/exist", beego.BeforeRouter, areaApiPermission)

	beego.Router("/api/areaname/validate/exist", &controllers.AreasManageController{}, "POST:PostAreaNameValidateExist")
	beego.InsertFilter("/api/areaname/validate/exist", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/area/selector", &controllers.AreasManageController{}, "GET:GetAreaSelector")
	beego.InsertFilter("/api/area/selector", beego.BeforeRouter, areaApiPermission)

	beego.Router("/api/school/selector", &controllers.SchoolsManageController{}, "GET:GetSchoolSelector")
	beego.InsertFilter("/api/school/selector", beego.BeforeRouter, areaApiPermission)

	beego.Router("/api/school/list", &controllers.SchoolsManageController{}, "Get:GetSchoolList")
	beego.InsertFilter("/api/school/list", beego.BeforeRouter, areaApiPermission)

	beego.Router("/api/schoolcode/validate/exist", &controllers.SchoolsManageController{}, "Post:PostSchoolCodeValidateExist")
	beego.InsertFilter("/api/schoolcode/validate/exist", beego.BeforeRouter, areaApiPermission)

	beego.Router("/api/school/modify", &controllers.SchoolsManageController{}, "Post:PostSchoolModify")
	beego.InsertFilter("/api/school/modify", beego.BeforeRouter, areaApiPermission)

	beego.Router("/api/school/add", &controllers.SchoolsManageController{}, "Post:PostSchoolAdd")
	beego.InsertFilter("/api/school/add", beego.BeforeRouter, areaApiPermission)

	beego.Router("/api/school", &controllers.SchoolsManageController{}, "Delete:DeleteSchool")
	beego.InsertFilter("/api/school", beego.BeforeRouter, areaApiPermission)

	beego.Router("/api/area", &controllers.AreasManageController{}, "DELETE:DeleteArea")
	beego.InsertFilter("api/area", beego.BeforeRouter, adminPermission)

	beego.Router("/api/student/list", &controllers.StudentsManageController{}, "Get:GetStudentsList")
	beego.InsertFilter("/api/school/list", beego.BeforeRouter, schoolApiPermission)

	beego.Router("/api/schoolrollid/validate/exist", &controllers.StudentsManageController{}, "Post:PostSchoolRollIdValidateExist")
	beego.InsertFilter("/api/schoolrollid/validate/exist", beego.BeforeRouter, schoolApiPermission)

	beego.Router("/api/studentphone/validate/exist", &controllers.StudentsManageController{}, "Post:PostStudentPhoneExist")
	beego.InsertFilter("/api/studentphone/validate/exist", beego.BeforeRouter, schoolApiPermission)

	beego.Router("/api/student/modify", &controllers.StudentsManageController{}, "Post:PostStudentModify")
	beego.InsertFilter("/api/student/modify", beego.BeforeRouter, schoolApiPermission)

	beego.Router("/api/school/schooltype", &controllers.SchoolsManageController{}, "Get:GetSchoolType")
	beego.InsertFilter("/api/student/schooltype", beego.BeforeRouter, schoolApiPermission)

	beego.Router("/api/student/add", &controllers.StudentsManageController{}, "Post:PostStudentAdd")
	beego.InsertFilter("/api/student/add", beego.BeforeRouter, schoolApiPermission)

	beego.Router("/api/student", &controllers.StudentsManageController{}, "Delete:DeleteStudent")
	beego.InsertFilter("/api/student", beego.BeforeRouter, schoolApiPermission)

	beego.Router("/api/area/import/check", &controllers.AreasManageController{}, "POST:PostAreasImportCheck")
	beego.Router("/api/area/import/submit", &controllers.AreasManageController{}, "POST:PostAreasImportSubmit")
	beego.InsertFilter("api/area/import/*", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/school/import/check", &controllers.SchoolsManageController{}, "POST:PostSchoolsImportCheck")
	beego.Router("/api/school/import/submit", &controllers.SchoolsManageController{}, "POST:PostSchoolsImportSubmit")
	beego.InsertFilter("/api/school/import/*", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/physical/import/check", &controllers.PhysicalManageController{}, "POST:PostPhysicalImportCheck")
	beego.Router("/api/physical/import/submit", &controllers.PhysicalManageController{}, "POST:PostPhysicalImportSubmit")
	beego.InsertFilter("/api/physical/import/*", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/visualization/data", &controllers.PhysicalManageController{}, "Get:GetVisualizationData")
	beego.InsertFilter("/api/visualization/data", beego.BeforeRouter, schoolApiPermission)

	beego.Router("/api/physical/list", &controllers.PhysicalManageController{}, "Get:GetPhysicalList")
	beego.InsertFilter("/api/physical/list", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/physical/modify", &controllers.PhysicalManageController{}, "Post:PostPhysicalModify")
	beego.InsertFilter("/api/physical/modify", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/label/validate/exist", &controllers.LabelManageController{}, "Post:PostValidateLabel")
	beego.InsertFilter("/api/label/validate/exist", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/label/add", &controllers.LabelManageController{}, "Post:PostLabelAdd")
	beego.InsertFilter("/api/label/add", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/label/list", &controllers.LabelManageController{}, "Get:GetLabelList")
	beego.InsertFilter("/api/label/list", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/label/modify", &controllers.LabelManageController{}, "Post:PostLabelModify")
	beego.InsertFilter("/api/label/modify", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/label", &controllers.LabelManageController{}, "Delete:DeleteLabel")
	beego.InsertFilter("/api/label", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/index/map", &controllers.ProvinceController{}, "Get:GetIndexMap")
	beego.InsertFilter("/api/index/map", beego.BeforeRouter, schoolApiPermission)

	beego.Router("/api/area/overview", &controllers.AreasManageController{}, "Get:GetAreaOverview")
	beego.InsertFilter("/api/area/overview", beego.BeforeRouter, schoolApiPermission)

	beego.Router("/api/area/school-rank", &controllers.AreasManageController{}, "Get:GetSchoolRank")
	beego.InsertFilter("/api/area/school-rank", beego.BeforeRouter, schoolApiPermission)

	beego.Router("/api/school/overview", &controllers.SchoolsManageController{}, "Get:GetSchoolOverview")
	beego.InsertFilter("/api/school/overview", beego.BeforeRouter, schoolApiPermission)

	beego.Router("/api/report/package/list", &controllers.ReportManageController{}, "Get:GetReportPackageList")
	beego.InsertFilter("/api/report/package/list", beego.BeforeRouter, areaApiPermission)

	beego.Router("/api/report/school", &controllers.ReportManageController{}, "Get:GetReportSchool")
	beego.InsertFilter("/api/report/school", beego.BeforeRouter, schoolApiPermission)

	beego.Router("/api/report/school/exist", &controllers.ReportManageController{}, "Get:GetReportSchoolExist")
	beego.InsertFilter("/api/report/school/exist", beego.BeforeRouter, schoolApiPermission)

	beego.Router("/api/report/area/exist", &controllers.ReportManageController{}, "Get:GetReportAreaExist")
	beego.InsertFilter("/api/report/area/exist", beego.BeforeRouter, areaApiPermission)

	beego.Router("/api/report/area", &controllers.ReportManageController{}, "Get:GetReportArea")
	beego.InsertFilter("/api/report/area", beego.BeforeRouter, areaApiPermission)

	beego.Router("/api/report/city/exist", &controllers.ReportManageController{}, "Get:GetReportCityExist")
	beego.InsertFilter("/api/report/city/exist", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/report/city", &controllers.ReportManageController{}, "Get:GetReportCity")
	beego.InsertFilter("/api/report/city", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/report/province/exist", &controllers.ReportManageController{}, "Get:GetReportProvinceExist")
	beego.InsertFilter("/api/report/province/exist", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/report/province", &controllers.ReportManageController{}, "Get:GetReportProvince")
	beego.InsertFilter("/api/report/province", beego.BeforeRouter, areaApiPermission)

	beego.Router("/api/report/sub/list", &controllers.ReportManageController{}, "Get:GetReportSubList")
	beego.InsertFilter("/api/report/sub/list", beego.BeforeRouter, areaApiPermission)

	beego.Router("/api/report/sub", &controllers.ReportManageController{}, "Get:GetReportSub")
	beego.InsertFilter("/api/report/sub", beego.BeforeRouter, areaApiPermission)

	beego.Router("/api/report/sub/exist", &controllers.ReportManageController{}, "Get:GetReportSubExist")
	beego.InsertFilter("/api/report/exist", beego.BeforeRouter, areaApiPermission)

	beego.Router("/api/report/sub/mark-rebuild", &controllers.ReportManageController{}, "Post:PostReportSubMarkForRebuild")
	beego.InsertFilter("/api/report/sub/mark-rebuild", beego.BeforeRouter, areaApiPermission)

	beego.Router("/api/label/tag/list", &controllers.LabelManageController{}, "Get:GetLabelTagList")
	beego.InsertFilter("/api/label/tag/list", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/label/tag", &controllers.LabelManageController{}, "Post:PostLabelTag")
	beego.InsertFilter("/api/label/tag", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/label/tag", &controllers.LabelManageController{}, "Delete:DeleteLabelTag")
	beego.InsertFilter("/api/label/tag", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/captcha", &controllers.UserController{}, "Get:GetCaptcha")

	beego.Router("/api/manager/list", &controllers.UserController{}, "Get:GetManagerList")
	beego.InsertFilter("/api/manager/list", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/manager/password", &controllers.UserController{}, "POST:PostPasswordModify")
	beego.InsertFilter("/api/manager/password", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/manager/modify", &controllers.UserController{}, "Post:PostManagerModify")
	beego.InsertFilter("/api/manager/modify", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/user/has", &controllers.UserController{}, "Post:PostUserHas")
	beego.InsertFilter("/api/user/has", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/area/export", &controllers.AreasManageController{}, "Get:GetAreaExport")
	beego.InsertFilter("/api/area/export", beego.BeforeRouter, adminApiPermission)

	beego.Router("/api/school/export", &controllers.SchoolsManageController{}, "Get:GetSchoolExport")
	beego.InsertFilter("/api/school/export", beego.BeforeRouter, areaApiPermission)

	beego.Router("/api/student/export", &controllers.StudentsManageController{}, "Get:GetStudentExport")
	beego.InsertFilter("/api/student/export", beego.BeforeRouter, schoolApiPermission)

	beego.Router("/api/physical/export", &controllers.PhysicalManageController{}, "Get:GetPhysicalExport")
	beego.InsertFilter("/api/physical/export", beego.BeforeRouter, adminApiPermission)
	//beego.Router("/ap")
}
